package com.avicsafety.lib.baidumap;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;


import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/6/15.
 */

public class ChoosePlaceActivity extends Activity {
    //控件
    private MapView mMapView;
    private ProgressBar mLoadBar;
    private ImageView mSelectImg;
    private TextView tv_back;
    private Button btn_gps,btn_NORMAL,btn_SATELLITE;


    private BaiduMap mBaiduMap;
    //定位
    private LocationClient mLocationClient;
    private MyBDLocationListner mListner;

    private double mLantitude;  //纬度
    private double mLongtitude;  //经度


//    private LatLng mll;
    private LatLng currentLatLng;
    private LatLng currenLatLng;

    // 设置第一次定位标志
    private boolean isFirstLoc = true;

    // MapView中央对于的屏幕坐标 (物理位置)
    private Point mCenterPoint = null;

    //地理编码
    private GeoCoder mGeoCoder;

    //位置列表
    private ListView mListView;
    private List<PoiInfo> mInfoList;
    private PoiInfo mCurentInfo = new PoiInfo();
    private PlaceListAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_chooseplace);

        initUI();
        initMap();
        initLocation();
        initData();
        initEvent();
    }


    private void initUI() {
        //初始化控件
        mMapView = (MapView) findViewById(R.id.chooseplace_bmapView);
        tv_back = (TextView) findViewById(R.id.tv_back);
        btn_gps = (Button) findViewById(R.id.btn_gps);
        btn_NORMAL= (Button) findViewById(R.id.btn_NORMAL);
        btn_SATELLITE= (Button) findViewById(R.id.btn_SATELLITE);

        mListView = (ListView) findViewById(R.id.place_list);
        mLoadBar = (ProgressBar) findViewById(R.id.place_progressBar);
    }

    private void initData() {
        Intent intent = getIntent();
        mLantitude = intent.getDoubleExtra("lat", 0);
        mLongtitude = intent.getDoubleExtra("lng", 0);

        Log.e("纬度", mLantitude + "");
        Log.e("经度", mLongtitude + "");


    }

    private void initMap() {
        mMapView.showZoomControls(false); //设置是否显示缩放控件
        mBaiduMap = mMapView.getMap();  //获取BaiduMap的实例
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(17.0f);  //设置缩放级别
        mBaiduMap.setMapStatus(msu);
        mBaiduMap.setOnMapTouchListener(touchListener); //设置触摸地图事件监听者

        //初始化POI信息列表
        mInfoList = new ArrayList<PoiInfo>();

        //获取当前MapView中心物理坐标
        mCenterPoint = mBaiduMap.getMapStatus().targetScreen;
        // mll = mBaiduMap.getMapStatus().target;
        currentLatLng = mBaiduMap.getMapStatus().target;
    }


    private void initEvent() {
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        btn_gps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回上个界面,并带回当前位置的经纬度值,并且关闭当前界面
                Intent intent = new Intent();
                if (mCurentInfo.location == null) {         //防止未精确定位时用户点击“定位”出现bug  whb改
                    Toast.makeText(ChoosePlaceActivity.this,"请等待定位准确！",Toast.LENGTH_SHORT).show();
                } else {
                    //currenLatLng = mBaiduMap.getProjection().fromScreenLocation(mCenterPoint);
                    currentLatLng = mBaiduMap.getMapStatus().target;
                    mLantitude = currentLatLng.latitude;
                    mLongtitude = currentLatLng.longitude;
                    intent.putExtra("lat", mLantitude);
                    intent.putExtra("lng", mLongtitude);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

        btn_NORMAL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
            }
        });

        btn_SATELLITE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
            }
        });

    }


    private void initLocation() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {

            //定位
            mBaiduMap.setMyLocationEnabled(true);//设置是否允许定位层
            mLocationClient = new LocationClient(getApplicationContext());
            mListner = new MyBDLocationListner();
            mLocationClient.registerLocationListener(mListner);
            LocationClientOption option = new LocationClientOption();
            option.setOpenGps(true);  //打开GPS
            option.setCoorType("bd09ll");//设置坐标系类型
            option.setScanSpan(1000);
            mLocationClient.setLocOption(option);

            mLocationClient.start();

            //地理编码
            mGeoCoder = GeoCoder.newInstance();
            mGeoCoder.setOnGetGeoCodeResultListener(GeoListener);  //地理编码监听器

            //周边位置列表

            mListView.setOnItemClickListener(itemClickListener);  //设置ListView条目的点击事件
            mAdapter = new PlaceListAdapter(getLayoutInflater(), mInfoList);
            mListView.setAdapter(mAdapter);

            mSelectImg = new ImageView(ChoosePlaceActivity.this);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initLocation();
                } else {
                    finish();
                }
                return;
            }
        }
    }


    //回到原位的按钮的点击事件 定位当当前设备所在的位置
    public void turnBack(View view) {
        // 实现动画跳转
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(currentLatLng);
        mBaiduMap.animateMapStatus(u);

        mBaiduMap.clear();
        // 发起反地理编码检索
        mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption())
                .location(currentLatLng));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mGeoCoder.destroy();
    }

    /**
     * 定位监听器
     */
    private class MyBDLocationListner implements BDLocationListener {

        @Override
        public void onReceiveLocation(final BDLocation bdLocation) {
            //mapView 销毁后不再处理新接收的位置
            if (bdLocation == null || mMapView == null)
                return;
            MyLocationData data = new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius())
                    .latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(data);
            //设置自定义图标
            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null);

            mBaiduMap.setMyLocationConfiguration(config);

            if (mLantitude == 0.0 || mLongtitude == 0.0) {
                mLantitude = bdLocation.getLatitude();
                mLongtitude = bdLocation.getLongitude();
                Log.e("lat:", mLantitude + "");
                Log.e("lon:", mLongtitude + "");
            }
            currentLatLng = new LatLng(mLantitude, mLongtitude);

            //   mll = new LatLng(mLantitude, mLongtitude);


            // 是否第一次定位
            if (isFirstLoc) {
                isFirstLoc = false;
                // 实现动画跳转
                MapStatusUpdate u = MapStatusUpdateFactory
                        .newLatLng(currentLatLng);
                mBaiduMap.animateMapStatus(u);

                mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption())
                        .location(currentLatLng));
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    //地图触摸事件监听者
    BaiduMap.OnMapTouchListener touchListener = new BaiduMap.OnMapTouchListener() {
        @Override
        public void onTouch(MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (mCenterPoint == null) {
                    return;
                }
                //获取当前MapView中心屏幕坐标对应的地理坐标
                currenLatLng = mBaiduMap.getProjection().fromScreenLocation(mCenterPoint);
                //发起反地理编码检索
                mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption()).location(currenLatLng));
                mLoadBar.setVisibility(View.VISIBLE);//进度条显示
            }

        }
    };

    //地理编码监听器
    OnGetGeoCoderResultListener GeoListener = new OnGetGeoCoderResultListener() {
        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
            if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                //TODO
                Toast.makeText(ChoosePlaceActivity.this, "没有检索到结果", Toast.LENGTH_SHORT).show();
            }
            // 获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                // 没有找到检索结果
                Toast.makeText(ChoosePlaceActivity.this, "没有检索到结果", Toast.LENGTH_SHORT).show();
            } else {
                //当前位置信息

                mCurentInfo.address = reverseGeoCodeResult.getAddress();
                mCurentInfo.location = reverseGeoCodeResult.getLocation();
                mCurentInfo.name = "[位置]";
                mInfoList.clear();
                mInfoList.add(mCurentInfo);


                //将周边信息加入表
                if (reverseGeoCodeResult.getPoiList() != null) {
                    mInfoList.addAll(reverseGeoCodeResult.getPoiList());
                }
                //刷新数据
                mAdapter.notifyDataSetChanged();
                mLoadBar.setVisibility(View.GONE);//进度条消失
            }
        }
    };

    // listView选项点击事件监听器
    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

            // 通知是适配器第position个item被选择了
            mAdapter.setNotifyTip(position);

            BitmapDescriptor mSelectIco = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
            mBaiduMap.clear();
            PoiInfo info = (PoiInfo) mAdapter.getItem(position);
            LatLng la = info.location;

            //动画跳转
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(la);
            mBaiduMap.animateMapStatus(u);

            //添加覆盖物
            OverlayOptions ooA = new MarkerOptions().position(la).icon(mSelectIco).anchor(0.5f, 0.5f);
            mBaiduMap.addOverlay(ooA);

            //选中项打勾
            mSelectImg.setBackgroundResource(R.drawable.greywhite);
            mSelectImg = (ImageView) view.findViewById(R.id.place_select);
            mSelectImg.setBackgroundResource(R.drawable.ic_select);

        }
    };


}
